package com.lab.project.visitor.record.service.impl;

import com.lab.common.utils.DateUtils;
import com.lab.common.utils.ParameterUtil;
import com.lab.common.utils.bean.BeanUtils;
import com.lab.project.visitor.domain.*;
import com.lab.project.visitor.domain.vo.UserVO;
import com.lab.project.visitor.domain.vo.VisitorRecordVO;
import com.lab.project.visitor.record.enums.ErrorType;
import com.lab.project.visitor.record.mapper.*;
import com.lab.project.visitor.record.service.IVisitorService;
import com.lab.project.visitor.verification.utils.Base64Save;
import com.lab.project.visitor.verification.utils.SnowflakeIdUtil;
import com.neusiri.ai.api.yitu.box.face.entity.FaceExtraMeta;
import com.neusiri.ai.api.yitu.gateway.repository.entity.PersonOperation;
import com.neusiri.ai.sdk.box.service.BoxService;
import com.neusiri.ai.sdk.gateway.service.GatewayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 黄晏凯
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class VisitorServiceImpl implements IVisitorService {
    @Resource
    private VisitorMapper visitorMapper;
    @Resource
    private VisitorRecordMapper visitorRecordMapper;
    @Resource
    private VisitorFaceMapper visitorFaceMapper;
    @Resource
    private VisitorDeviceMapper visitorDeviceMapper;
    @Resource
    private VisitorUserMapper visitorUserMapper;
    @Resource
    private DeviceFaceMapper deviceFaceMapper;
    @Resource
    private VisitorRecordFaceMapper visitorRecordFaceMapper;
    @Resource
    private VisitorUserEntity visitorUserEntity;
    /**
     * 人脸面板的服务
     */
    @Resource
    private GatewayService gatewayService;
    /**
     * 与盒子通信的服务
     */
    @Resource
    private BoxService boxService;
    @Value("${ai-sdk.face-database}")
    private String faceDatabaseId;
    /**
     * 待完善
     */
    private static String UNACCOMPLISHED = "0";

    @Override
    public List<DeviceEntity> listDevice() {
        return visitorMapper.listDevice();
    }


    /**
     * @param visitorRecordVO
     * @return
     */
    @Override
    public String saveVisitor(VisitorRecordVO visitorRecordVO) {
        //通过身份证在数据库里查询用户时候存在
        List<UserVO> user = getVisitorUserByIdCard(visitorRecordVO.getUserIdCard());
        //用户不存在添加user表
        if (user == null || user.isEmpty()) {
            log.info("======判断用户是否存在（不存在）======");
            int i = addVisitorUser(visitorRecordVO);
            log.info("=================用户添加完毕======{}条记录", i);
        } else {
            //用户存在就更改信息。
            updateVisitorUser(visitorRecordVO);
        }

        //通过userIdCard查询访客记录
        List<VisitorRecordEntity> recordList = visitorRecordMapper.getRecordListByIdCard(visitorRecordVO.getUserIdCard());
        //没有访客信息或者访客已结束
        if (recordList == null || isVisitStatus(recordList).equals("2")) {
            //保存记录
            saveRecord(visitorRecordVO);
        } else if (isVisitStatus(recordList).equals("0")) {
            visitorRecordVO.setVisitStatus("1");
            VisitorRecordEntity recordEntity = new VisitorRecordEntity();
            BeanUtils.copyBeanProp(recordEntity,visitorRecordVO);
            ParameterUtil.setUpdateEntity(recordEntity);
            visitorRecordMapper.updateRecord(recordEntity);
            Long userId = visitorUserMapper.getVisitorUserByIdCard(visitorRecordVO.getUserIdCard());
            addInfoToDevice(visitorRecordVO,visitorRecordVO.getId(),userId);
        } else {
            //返回”当前人员存在状态为来访中的记录,保存失败“
            return ErrorType.STATUS_ING_ERROR.getCode();
        }
        //访客记录数据保存成功
        return ErrorType.MESSAGE_SUCCESS.getCode();
    }

    private boolean isFacePicUrl(List<FaceEntity> faceEntityList, String url) {
        for (FaceEntity faceEntity : faceEntityList) {
            if (faceEntity.getFacePicUrl().equals(url)) {
                return true;
            }
        }
        return false;
    }

    private String saveRecord(VisitorRecordVO visitorRecordVO) {
        Long userId = visitorUserMapper.getVisitorUserByIdCard(visitorRecordVO.getUserIdCard());
        //添加访客记录表
        Long visitorRecordId = addVisitorRecord(visitorRecordVO);
        List<FaceEntity> faceEntityList = visitorFaceMapper.getFaceEntityByUserId(userId);
        if (faceEntityList == null || faceEntityList.isEmpty()) {
            // 添加face表
            Long faceId = addVisitorFace(visitorRecordVO);
            //添加人脸数据
            addVisitorDeviceFace(faceId, visitorRecordId, visitorRecordVO);
        } else if (!isFacePicUrl(faceEntityList, visitorRecordVO.getFacePicUrl())) {
            Long faceId = addVisitorFace(visitorRecordVO);
            //添加人脸数据
            addVisitorDeviceFace(faceId, visitorRecordId, visitorRecordVO);
        }


        //判断是否添加了设备id
        if (visitorRecordVO.getDeviceId() != null) {
            addInfoToDevice(visitorRecordVO, visitorRecordId, userId);
        }


        return ErrorType.MESSAGE_SUCCESS.getCode();
    }

    /**
     * 添加信息到box，面板，
     * @param visitorRecordVO
     * @param visitorRecordId
     * @param userId
     * @return
     */
    private String addInfoToDevice(VisitorRecordVO visitorRecordVO, Long visitorRecordId, Long userId) {
        // 添加数据到访客设备表
        addVisitorDeviceInfo(visitorRecordVO, visitorRecordId);
        byte[] image = Base64Save.imageToByteBufferByOnline(visitorRecordVO.getFacePicUrl());
        FaceExtraMeta faceExtraMeta = new FaceExtraMeta();
        faceExtraMeta.setGender(visitorRecordVO.getUserSex());
        faceExtraMeta.setName(visitorRecordVO.getUserName());
        faceExtraMeta.setId(visitorRecordVO.getUserIdCard());
        //添加人脸信息到设备上。
            /*boxService.getBoxFaceService().addFace(faceDatabaseId,
                    String.valueOf(faceId),
                    image,
                    FacePicEnum.JPEG, faceExtraMeta);*/
        //获取访客有权限的设备
        List<DeviceEntity> userDeviceList = visitorDeviceMapper.getUserDeviceList(visitorRecordVO.getDeviceId());
        //给设备添加信息（给访客发放设备权限）
        if (userDeviceList.size() > 0) {
            for (DeviceEntity entity : userDeviceList) {
                PersonOperation personOperation = new PersonOperation();
                log.info("========userId=========={}=======", userId);
                personOperation.setId(String.valueOf(userId));
                personOperation.setName(visitorRecordVO.getUserName());
                personOperation.setPicBytes(image);
                personOperation.setCardNo(visitorRecordVO.getUserIdCard());
                gatewayService.getGatewayRepositoryService().addPerson(personOperation, entity.getDeviceIp());
            }
        }
        return ErrorType.MESSAGE_SUCCESS.getCode();
    }

    /**
     * 判断用户来访状态 （0：待完善；1：来访中；2：已结束）
     *
     * @param recordList
     * @return String 来访状态（0：待完善；1：来访中；2：已结束）
     */
    private String isVisitStatus(List<VisitorRecordEntity> recordList) {
        for (VisitorRecordEntity list : recordList) {
            if (list.getVisitStatus().equals("1")) {
                return "1";
            }
            if (list.getVisitStatus().equals("0")) {
                return "0";
            }
        }
        return "2";
    }


    /**
     * 添加人脸数据
     *
     * @param faceId
     * @param recordId
     */
    private void addVisitorDeviceFace(Long faceId, Long recordId, VisitorRecordVO visitorRecordVO) {
        VisitorRecordFaceEntity visitorRecordFaceEntity = new VisitorRecordFaceEntity();
        //设置faceId
        visitorRecordFaceEntity.setFaceId(faceId);
        //设置recordId
        visitorRecordFaceEntity.setRecordId(recordId);
        //设置faceDatabaseId
        visitorRecordFaceEntity.setFaceDatabaseId(Long.valueOf(faceDatabaseId));
        visitorRecordFaceEntity.setCreateBy(visitorRecordVO.getCreateBy());
        //设置公共字段的数据
        ParameterUtil.setCreateEntity(visitorRecordFaceEntity);
        //调用mapper中的方法（保存数据）
        deviceFaceMapper.addVisitorDeviceFace(visitorRecordFaceEntity);
    }


    /**
     * 存访客的用户信息
     *
     * @return
     */
    private int addVisitorUser(VisitorRecordVO visitorRecordVO) {
        BeanUtils.copyBeanProp(visitorUserEntity, visitorRecordVO);
        // 判断是否是认证核验机传来的值
        //设置一些公共的值
        ParameterUtil.setCreateEntity(visitorUserEntity);
//        把人员状态设为启动状态
//        人员状态（0：启用；1：停用；2：黑名单）
        visitorUserEntity.setUserStatus("0");
        visitorUserEntity.setId(SnowflakeIdUtil.getSnowflakeId());
        int i = visitorMapper.addVisitorUser(visitorUserEntity);
        return i;
    }

    /**
     * 存访客记录信息
     *
     * @return
     */
    private Long addVisitorRecord(VisitorRecordVO visitorRecordVO) {
        VisitorRecordEntity visitorRecordEntity = new VisitorRecordEntity();
        BeanUtils.copyBeanProp(visitorRecordEntity, visitorRecordVO);
        //设置一些公共的值
        ParameterUtil.setCreateEntity(visitorRecordEntity);
        Long userId = visitorUserMapper.getVisitorUserByIdCard(visitorRecordVO.getUserIdCard());
        //设置t_visitor_record表中对应的t_user_id
        visitorRecordEntity.setTUserId(userId);
        visitorMapper.addVisitorRecord(visitorRecordEntity);
        Long id = visitorRecordEntity.getId();
        return id;
    }

    /**
     * 添加访客人脸信息
     *
     * @return
     */
    private Long addVisitorFace(VisitorRecordVO visitorRecordVO) {
        VisitorFaceEntity visitorFaceEntity = new VisitorFaceEntity();
        BeanUtils.copyBeanProp(visitorFaceEntity, visitorRecordVO);
        ParameterUtil.setCreateEntity(visitorFaceEntity);
        visitorFaceEntity.setId(SnowflakeIdUtil.getSnowflakeId());
        Long userId = visitorUserMapper.getVisitorUserByIdCard(visitorRecordVO.getUserIdCard());
        visitorFaceEntity.setTUserId(userId);
        visitorFaceMapper.addVisitorFace(visitorFaceEntity);
        return visitorFaceEntity.getId();
    }

    /**
     * 添加权限设备信息
     *
     * @param visitorRecordVO
     * @param visitorRecordId
     */
    private void addVisitorDeviceInfo(VisitorRecordVO visitorRecordVO, Long visitorRecordId) {
        VisitorDeviceEntity visitorDeviceEntity = new VisitorDeviceEntity();
        BeanUtils.copyBeanProp(visitorDeviceEntity, visitorRecordVO);
        ParameterUtil.setCreateEntity(visitorDeviceEntity);
        visitorDeviceEntity.setRecordId(visitorRecordId);
        visitorDeviceMapper.addVisitorDeviceInfo(visitorDeviceEntity);
    }

    /**
     * 根据身份证修改信息
     *
     * @param visitorRecordVO
     * @return
     */
    public int updateVisitorUser(VisitorRecordVO visitorRecordVO) {
        BeanUtils.copyBeanProp(visitorUserEntity, visitorRecordVO);
        ParameterUtil.setCreateEntity(visitorUserEntity);
        return visitorUserMapper.updateVisitorUser(visitorUserEntity);
    }

    /**
     * 查询访客记录信息
     *
     * @return
     */
    @Override

    public List<VisitorRecordVO> listVisitor(VisitorRecordVO visitorRecordVO) {
        List<VisitorRecordVO> visitorRecordVOS = visitorRecordMapper.listVisitor(visitorRecordVO);
        return visitorRecordVOS;
    }

    /**
     * 通过身份证查询用户
     *
     * @return
     */
    @Override
    public List<UserVO> getVisitorUserByIdCard(String userIdCard) {
        List<UserVO> visitorUser = visitorUserMapper.getUserVOByIdCard(userIdCard);
        return visitorUser;
    }

    /**
     * 解释访问
     *
     * @param visitorRecordVO
     * @return
     */
    @Override
    public String endVisitorStatus(VisitorRecordVO visitorRecordVO) {
        log.info("===========visitorRecordVO.getId()================={}", visitorRecordVO.getId());
        Long userId = visitorUserMapper.getUserIdById(visitorRecordVO.getId());
        log.info("=========userId========={}====", userId);
        VisitorRecordEntity visitorRecordEntity = new VisitorRecordEntity();
        BeanUtils.copyBeanProp(visitorRecordEntity, visitorRecordVO);
        visitorRecordEntity.setActualVisitEndTime(DateUtils.getNowDate());

        // 通过id查询record_face表的faceId
        Long faceId = visitorRecordFaceMapper.getFaceIdByRecordId(visitorRecordEntity.getId());
        // 删除人脸面板上的人脸
        List<DeviceEntity> devices = visitorDeviceMapper.getDeviceListByRecordId(visitorRecordEntity.getId());
        if (devices.size() > 0) {
            for (DeviceEntity device : devices) {
                log.info("==============device============={}", device);
                gatewayService.getGatewayRepositoryService().removePerson(String.valueOf(userId), device.getDeviceIp());
            }
        }
        // 删除盒子中的人脸
        //boxService.getBoxRepositoryService().removeRepository(faceId.toString());

        int i = visitorRecordMapper.endVisitorStatus(visitorRecordEntity);
        return ErrorType.END_VISITOR_SUCCESS.getCode();
    }

    @Override
    public String deleteVisitorRecord(Long[] ids) {

        for (Long id : ids) {
            // 删除表(逻辑删除)
            VisitorRecordEntity visitorRecordEntity = new VisitorRecordEntity();
            ParameterUtil.setUpdateEntity(visitorRecordEntity);
            visitorRecordEntity.setId(id);
            visitorRecordMapper.deleteRecordById(visitorRecordEntity);
        }

        return "00";
    }
}
